package com.example.aussiehealthhelper;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SymptomSearchActivity extends AppCompatActivity {

    private HealthDbHelper dbHelper;
    private List<String> symptomCategories;
    private List<CheckBox> symptomCheckboxes = new ArrayList<>();
    private DrugAdapter drugAdapter;
    private TextView selectedSymptomsView;
    private Spinner categorySpinner;
    private LinearLayout symptomsContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_symptom_search);

        dbHelper = new HealthDbHelper(this);

        //从数据库获取所有适应症类别
        symptomCategories = new ArrayList<>();
        symptomCategories.add("请选择症状类别");

        //获取并过滤空值
        List<String> dbCategories = dbHelper.getAllIndicationCategories();
        for (String category : dbCategories) {
            if (category != null && !category.trim().isEmpty()) {
                symptomCategories.add(category);
            }
        }

        if (symptomCategories.size() == 1) {
            symptomCategories.add("感冒发烧类");
            symptomCategories.add("消化系统类");
            symptomCategories.add("皮肤外用类");
        }

        categorySpinner = findViewById(R.id.categorySpinner);
        symptomsContainer = findViewById(R.id.symptomsContainer);
        selectedSymptomsView = findViewById(R.id.selectedSymptomsView);

        setupCategorySpinner();
        setupSelectedSymptomsView();
        setupSearchButton();
        setupClearButton();
        setupDrugList();

        displayPopularDrugs();
    }

    //设置症状类别下拉菜单
    private void setupCategorySpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                symptomCategories
        );

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categorySpinner.setAdapter(adapter);

        //类别选择
        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //第一项是提示，不显示症状
                if (position == 0) {
                    symptomsContainer.removeAllViews();
                    return;
                }

                //获取选中的类别
                String selectedCategory = symptomCategories.get(position);
                displaySymptomsForCategory(selectedCategory);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //显示当前类别的症状选项
    private void displaySymptomsForCategory(String category) {
        Log.d("SymptomSearch", "正在显示类别: " + category);
        symptomsContainer.removeAllViews();
        symptomCheckboxes.clear();

        //使用Set自动去重
        Set<String> uniqueSymptoms = new HashSet<>();

        //获取该类别的所有药品
        List<Drug> drugs = getDrugsForCategory(category);

        Log.d("SymptomSearch", "找到药品数量: " + (drugs != null ? drugs.size() : 0));

        if (drugs == null || drugs.isEmpty()) {
            showNoSymptomsMessage("该类别暂无症状数据");
            return;
        }

        //提取所有药品的症状（按斜杠分割）
        for (Drug drug : drugs) {
            String indication = drug.getIndication();
            if (indication != null && !indication.isEmpty()) {
                Log.d("SymptomSearch", "药品适应症: " + indication);

                // 按斜杠分隔症状
                String[] symptoms = indication.split("/");
                for (String symptom : symptoms) {
                    String trimmed = symptom.trim();
                    if (!trimmed.isEmpty()) {
                        // 确保症状不是重复的
                        boolean alreadyExists = false;
                        for (String existingSymptom : uniqueSymptoms) {
                            if (existingSymptom.equalsIgnoreCase(trimmed)) {
                                alreadyExists = true;
                                break;
                            }
                        }

                        if (!alreadyExists) {
                            uniqueSymptoms.add(trimmed);
                            Log.d("SymptomSearch", "添加症状: " + trimmed);
                        }
                    }
                }
            }
        }

        if (uniqueSymptoms.isEmpty()) {
            showNoSymptomsMessage("该类别暂无症状数据");
            return;
        }

        Log.d("SymptomSearch", "提取出的独特症状数量: " + uniqueSymptoms.size());

        //将症状排序后显示
        List<String> sortedSymptoms = new ArrayList<>(uniqueSymptoms);
        Collections.sort(sortedSymptoms);

        for (String symptom : sortedSymptoms) {
            CheckBox checkBox = new CheckBox(this);
            checkBox.setText(symptom);
            checkBox.setTag(symptom);
            checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    addSelectedSymptom(symptom);
                } else {
                    removeSelectedSymptom(symptom);
                }
                updateSelectedSymptomsView();
            });
            symptomsContainer.addView(checkBox);
            symptomCheckboxes.add(checkBox);
        }
    }

    private List<Drug> getDrugsForCategory(String category) {
        //精确匹配
        List<Drug> drugs = dbHelper.getDrugsByCategory(category);
        if (drugs != null && !drugs.isEmpty()) {
            return drugs;
        }

        Log.d("SymptomSearch", "精确匹配失败: " + category);

        //智能匹配
        for (String dbCategory : dbHelper.getAllIndicationCategories()) {
            if (dbCategory != null && dbCategory.contains(category)) {
                drugs = dbHelper.getDrugsByCategory(dbCategory);
                if (drugs != null && !drugs.isEmpty()) {
                    Log.d("SymptomSearch", "智能匹配成功: " + dbCategory);
                    return drugs;
                }
            }
        }

        Log.d("SymptomSearch", "智能匹配失败");
        return new ArrayList<>();
    }

    private void showNoSymptomsMessage(String message) {
        TextView noSymptoms = new TextView(this);
        noSymptoms.setText(message);
        noSymptoms.setPadding(16, 16, 16, 16);
        symptomsContainer.addView(noSymptoms);
    }

    private void setupSelectedSymptomsView() {
        selectedSymptomsView.setVisibility(View.GONE);
    }

    private void updateSelectedSymptomsView() {
        List<String> selected = getSelectedSymptoms();
        if (!selected.isEmpty()) {
            selectedSymptomsView.setText("已选症状: " + String.join(", ", selected));
            selectedSymptomsView.setVisibility(View.VISIBLE);
        } else {
            selectedSymptomsView.setVisibility(View.GONE);
        }
    }

    private void setupSearchButton() {
        Button searchButton = findViewById(R.id.searchButton);
        searchButton.setOnClickListener(v -> searchDrugsBySymptoms());
    }

    private void setupClearButton() {
        Button clearButton = findViewById(R.id.clearButton);
        clearButton.setOnClickListener(v -> {
            //清除所有选择
            for (CheckBox checkBox : symptomCheckboxes) {
                checkBox.setChecked(false);
            }
            //重置类别选择
            categorySpinner.setSelection(0);
            selectedSymptomsView.setVisibility(View.GONE);
            //重新显示热门药品
            displayPopularDrugs();
        });
    }

    //显示前十个药品
    private void displayPopularDrugs() {
        List<Drug> drugs = dbHelper.getAllDrugs();
        if (drugs.size() > 10) {
            drugs = drugs.subList(0, 10);
        }
        drugAdapter.updateData(drugs);
    }

    private List<String> getSelectedSymptoms() {
        List<String> selected = new ArrayList<>();
        for (CheckBox checkBox : symptomCheckboxes) {
            if (checkBox.isChecked()) {
                selected.add(checkBox.getText().toString());
            }
        }
        return selected;
    }

    private void addSelectedSymptom(String symptom) {
        for (CheckBox checkBox : symptomCheckboxes) {
            if (symptom.equals(checkBox.getText().toString())) {
                checkBox.setChecked(true);
                break;
            }
        }
    }

    private void removeSelectedSymptom(String symptom) {
        for (CheckBox checkBox : symptomCheckboxes) {
            if (symptom.equals(checkBox.getText().toString())) {
                checkBox.setChecked(false);
                break;
            }
        }
    }

    //搜索逻辑
    private void searchDrugsBySymptoms() {
        List<String> selectedSymptoms = getSelectedSymptoms();

        if (selectedSymptoms.isEmpty()) {
            displayPopularDrugs();
            return;
        }

        //使用数据库方法进行搜索
        List<Drug> matchedDrugs = dbHelper.findDrugsBySymptoms(selectedSymptoms);

        if (matchedDrugs == null || matchedDrugs.isEmpty()) {
            //显示空结果信息
            drugAdapter.updateData(new ArrayList<>());
            Toast.makeText(this, "没有找到匹配的药品", Toast.LENGTH_SHORT).show();
            return;
        }

        //排序：按匹配症状数量降序
        Collections.sort(matchedDrugs, (d1, d2) -> {
            int count1 = countMatchingSymptoms(d1.getIndication(), selectedSymptoms);
            int count2 = countMatchingSymptoms(d2.getIndication(), selectedSymptoms);
            return Integer.compare(count2, count1);
        });

        drugAdapter.updateData(matchedDrugs);
    }

    private int countMatchingSymptoms(String indication, List<String> selectedSymptoms) {
        if (indication == null) return 0;
        int count = 0;
        for (String symptom : selectedSymptoms) {
            //使用contains进行部分匹配
            if (indication.contains(symptom)) {
                count++;
            }
        }
        return count;
    }

    private void setupDrugList() {
        RecyclerView recyclerView = findViewById(R.id.drugsRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        drugAdapter = new DrugAdapter(new ArrayList<>(), this::openDrugDetails);
        recyclerView.setAdapter(drugAdapter);
    }

    private void openDrugDetails(Drug drug) {
        Intent intent = new Intent(this, DrugDetailActivity.class);
        intent.putExtra("DRUG_ID", drug.getId());
        startActivity(intent);
    }
}